package com.youmingxing.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.youmingxing.AllStarApp;
import com.youmingxing.R;
import com.youmingxing.activity.SearchActivity;
import com.youmingxing.adpter.ContentListAdapter;
import com.youmingxing.bean.Content;
import com.youmingxing.bean.SectionContent;
import com.youmingxing.network.AllStarApi;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.utils.DisplayUtil;
import com.youmingxing.utils.SharePreferenceUtil;
import com.youmingxing.view.DialogManager;
import com.youmingxing.view.RefreshListView;
import com.youmingxing.view.clipheadphoto.clip1.msg.BaseMessage;
import com.youmingxing.view.clipheadphoto.clip1.msg.MessageCenter;
import com.youmingxing.view.clipheadphoto.clip1.msg.MessageListenerDelegate;
import com.youmingxing.view.clipheadphoto.clip1.msg.MessageTable;
import com.youmingxing.view.clipheadphoto.clip1.msg.MessageWithInt;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * 广场页面内部的作品列表
 *
 * @author evilyin(ChenZhixi)
 * @since 15/9/4
 */
public class ContentListFragment extends Fragment implements MessageListenerDelegate {

    private View view;
    private ContentListAdapter adapter;
    private PtrClassicFrameLayout ptrLayout;
    private List<Content> list = new ArrayList<>();

    private int type; //1是热门，2是最新，3是关注
    private RefreshListView contentListView;
    private RelativeLayout errorLayout;
    private BaseJsonHandler initHandler;
    private BaseJsonHandler loadHandler;
    private View bannerView = null;
    private LinearLayout bannerLayout;
    private Context appContext = AllStarApp.getInstance();
    private TextView newTips;
    SharePreferenceUtil sharePreferenceUtil;
    boolean firstLoad = true;
    private boolean isRunning = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MessageCenter.getInstance().registerListener(this, MessageTable.iSRunning);
        sharePreferenceUtil = new SharePreferenceUtil(getActivity(), "time");
        Bundle bundle = getArguments();
        if (bundle != null) {
            type = bundle.getInt("type");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_content_list, container, false);
            contentListView = (RefreshListView) view.findViewById(R.id.content_list_view);
            ptrLayout = (PtrClassicFrameLayout) view.findViewById(R.id.ptr_layout);
            errorLayout = (RelativeLayout) view.findViewById(R.id.error);
            adapter = new ContentListAdapter(getActivity());
            newTips = (TextView) view.findViewById(R.id.new_tips);
            initHandlers();
            initData();

            ptrLayout.setLastUpdateTimeRelateObject(this);
            ptrLayout.setPtrHandler(new PtrHandler() {
                @Override
                public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
                    return PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, view, view1);
                }

                @Override
                public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                    refresh();
                }
            });

            View headerView = inflater.inflate(R.layout.header_search, null);
            headerView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getActivity().startActivity(new Intent(getActivity(), SearchActivity.class));
                }
            });

            contentListView.addHeaderView(headerView);
            contentListView.setAdapter(adapter);

            contentListView.setOnLoadMoreListener(new RefreshListView.OnLoadMoreListener() {
                @Override
                public void onLoadMore() {
                    loadData();
                }
            });
            errorLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DialogManager.showDialog(getActivity(), "正在拼命加载");
                    initData();
                }
            });
        }
        newTips.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initData();
            }
        });
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!firstLoad) {
            getTips();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        MessageCenter.getInstance().removeListenerFromMessage(this, MessageTable.iSRunning);
    }

    private void getTips() {
//        Log.i("----getTips---",type +"   "  +isRunning);
        if (isRunning) {
            return;
        }

        isRunning = true;
        long time = sharePreferenceUtil.getLastupdatetime(type);
        AllStarApi.getNewsCount(type, time, new BaseJsonHandler(getActivity()) {
            @Override
            public void onSuccessWithData(JSONObject response) {
//                Log.i("----getTips---0--",type +"   "  +response);
                firstLoad = true;  //  如果没有刷新那个提示一直存在
                newTips.setVisibility(View.GONE);
                int result = response.optJSONObject("data").optInt("result");
                if (result != 0) {
                    newTips.setVisibility(View.VISIBLE);
                    newTips.setText(response.optJSONObject("data").optString("tip"));
                    contentListView.setFadeTip(newTips);
                }
                sharePreferenceUtil.setLastupdatetime(type, System.currentTimeMillis());
            }
        });
    }

    private void initData() {
        getTips();
        firstLoad = false;
        switch (type) {
            case 1:
                AllStarApi.getBanner(1, new BaseJsonHandler(getActivity()) {
                    @Override
                    public void onSuccessWithData(JSONObject response) {
                        if (bannerView == null) {
                            bannerView = View.inflate(appContext, R.layout.header_banner, null);
                            bannerLayout = (LinearLayout) bannerView.findViewById(R.id.banner_layout);
                            contentListView.addHeaderView(bannerView);
                        }
                        JSONObject data = response.optJSONObject("data");
                        JSONArray contents = data.optJSONArray("contents");
                        if (contents.length() == 0) {
                            contentListView.removeHeaderView(bannerView);
                        } else {
                            if (bannerLayout.getChildCount() != contents.length()) {
                                bannerLayout.removeAllViews();
                                for (int i = 0; i < contents.length(); i++) {
                                    final SectionContent theContent = new SectionContent(contents.optJSONObject(i));
                                    ImageView image = new ImageView(getActivity());
                                    image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup
                                            .LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                                    Glide.with(getActivity().getApplicationContext()).load(theContent.img)
                                            .placeholder(R.drawable.banner_d).error(R.drawable.banner_d)
                                            .animate(R.anim.abc_fade_in).into(image);
                                    image.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            theContent.action.jump(getActivity());
                                        }
                                    });
                                    bannerLayout.addView(image);
                                }
                            } else {
                                for (int i = 0; i < contents.length(); i++) {
                                    final SectionContent theContent = new SectionContent(contents.optJSONObject(i));
                                    ImageView image = (ImageView) bannerLayout.getChildAt(i);
                                    Glide.with(getActivity().getApplicationContext()).load(theContent.img)
                                            .crossFade().into(image);
                                    image.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            theContent.action.jump(getActivity());
                                        }
                                    });
                                }
                            }
                        }
                    }
                });
                newTips.setVisibility(View.GONE);
            case 2:
                AllStarApi.getContents(type, -1, -1, initHandler);
                newTips.setVisibility(View.GONE);
                break;
            case 3:
                AllStarApi.getFocus(-1, -1, initHandler);
                newTips.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    private void initHandlers() {

        //初始化的handler
        initHandler = new BaseJsonHandler(getActivity()) {
            @Override
            public void onSuccessWithData(JSONObject response) {
                contentListView.reset();
                ptrLayout.setVisibility(View.VISIBLE);
                errorLayout.setVisibility(View.GONE);
                list.clear();
                JSONArray data = response.optJSONArray("data");
                if (data.length() != 0) {
                    for (int i = 0; i < data.length(); i++) {
                        Content thisContent = new Content(data.optJSONObject(i));
                        list.add(thisContent);
                    }

                } else {
                    if (type == 3) {
                        View v = View.inflate(appContext, R.layout.footer_no_data_focus, null);
                        v.setLayoutParams(new AbsListView.LayoutParams(DisplayUtil.getScreenWidth
                                (), DisplayUtil.getScreenHeightWithoutHeader() - 100));
                        ((ImageView) v.findViewById(R.id.hint_img)).setImageResource(R.mipmap.none_focus);
                        ((TextView) v.findViewById(R.id.hin1)).setText("您还没有关注任何人");
                        ((TextView) v.findViewById(R.id.hin2)).setText("");
                        contentListView.noData(v);
                    }
                }
                if (data.length() < 20) {
                    contentListView.noMoreData();
                }
                adapter.setData(list);
                ptrLayout.refreshComplete();
            }

            @Override
            public void onFail(int statusCode, String statusText) {
                super.onFail(statusCode, statusText);
                contentListView.endLoadMore();
                list.clear();
                if (type == 3) {
                    View v = View.inflate(appContext, R.layout.footer_no_data_focus, null);
                    v.setLayoutParams(new AbsListView.LayoutParams(DisplayUtil.getScreenWidth
                            (), DisplayUtil.getScreenHeightWithoutHeader() - 100));
                    ((ImageView) v.findViewById(R.id.hint_img)).setImageResource(R.mipmap.none_focus);
                    ((TextView) v.findViewById(R.id.hin1)).setText("您还没有关注任何人");
                    ((TextView) v.findViewById(R.id.hin2)).setText("");
                    contentListView.noData(v);
                }
                adapter.setData(list);
                adapter.notifyDataSetChanged();
                ptrLayout.refreshComplete();
                if (statusCode != 200 && statusCode != 40063) {
                    ptrLayout.setVisibility(View.GONE);
                    errorLayout.setVisibility(View.VISIBLE);
                }
            }
        };
        //加载更多的handler
        loadHandler = new BaseJsonHandler(getActivity()) {
            @Override
            public void onSuccessWithData(JSONObject response) {
                contentListView.endLoadMore();
                JSONArray data = response.optJSONArray("data");
                for (int i = 0; i < data.length(); i++) {
                    Content thisContent = new Content(data.optJSONObject(i));
                    list.add(thisContent);
                }
                adapter.setData(list);
                if (data.length() < 20) {
                    contentListView.noMoreData();
                }
            }

            @Override
            public void onFail(int statusCode, String statusText) {
                contentListView.endLoadMore();
                contentListView.noMoreData();
            }

        };

    }

    private void loadData() {

        if (list.size() > 0) {
            long addParam = 0;
            if (type == 1) {
                addParam = list.get(list.size() - 1).getHot();
            } else if (type == 2 || type == 3) {
                addParam = list.get(list.size() - 1).getCreatetime();
            }
            int id = list.get(list.size() - 1).getId();
            if (type == 3) {
                AllStarApi.getFocus(addParam, id, loadHandler);
            } else {
                AllStarApi.getContents(type, addParam, id, loadHandler);
            }
        }
    }

    private void refresh() {
        initData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (view != null) {
            if (view.getParent() != null) {
                ((ViewGroup) view.getParent()).removeView(view);
            }
        }
    }

    @Override
    public void onListenerExit() {

    }

    @Override
    public void getMessage(BaseMessage message) {
        if (message.getMsgId().equals(MessageTable.iSRunning)) {
            if (((MessageWithInt) message).getInt() == 2) {  //  往上滑动
                isRunning = false;
            } else {
                isRunning = true;
            }
        }
    }
}